5. Making API Requests
API requests are simply HTTP calls against a specified URI under
management.core.windows.net. For example, to list
all the hosted services underneath your account, you would need to make
an authenticated request to
https://management.core.windows.net/<subscription-id>/services/hostedservices.
Example 1 shows a sample program to
access the Windows Azure Service Management API. This is a simple
console application that accesses the Service Management API and
retrieves the list of hosted services.
Example 1. Sample API access
using System; using System.Linq; using System.Xml.Linq; using System.Text; using System.Security.Cryptography.X509Certificates; using System.Net; using System.IO;
namespace apidemo { class Program { static void Main(string[] args) { // Make request to URL under correct subscription-id // The long GUID is my subscription ID - you need to replace // that with yours to make this code work var req = (HttpWebRequest)WebRequest.Create( "https://management.core.windows.net/BD38CFDF-C191-4B09-B299- F706985CE348/services/hostedservices");
//Target right version of the API req.Headers.Add("x-ms-version:2009-10-01");
//Load the certificate created using makecert earlier req.ClientCertificates.Add( X509Certificate2.CreateFromCertFile("D:/preconfig.cer"));
//Read content and use XElement to pretty print it to the //console var respStream = req.GetResponse().GetResponseStream();
var xml = new StreamReader(respStream).ReadToEnd();
Console.WriteLine(XElement.Parse(xml));
Console.Read();
} } }
|
The program starts by constructing the right URL to make an HTTP
request to the API. Note that this code sample uses my subscription ID
(the long GUID in the middle of the URI); you would want to replace it
with your subscription ID. The API mandates that all calls specify which
version of the API the client expects. Only one version is out there
currently, so the code adds the x-ms-version header set to the right version
date.
At this point, you have an HTTPS request with the correct URI and
the correct headers. The last missing piece is the certificate. The code
attaches the X.509 certificate you created earlier. Note that although
the code points to the .cer file,
the Windows crypto APIs will look up the associated private key from the
certificate store. Finally, the code makes the request and prints out
the XML returned.
If everything worked, you should see output similar to Example 2. Note the little bit of XML
with the service name sriramktest.
This is essentially listing the same service displayed in the Developer
Portal back.
Example 2. Sample hosted services listing
<HostedServices xmlns=http://schemas.microsoft.com/windowsazure xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <HostedService> <Url>https://management.core.windows.net/BD38CFDF-C191-4B09-B299- F706985CE348/services/hostedservices/sriramktest</Url> <ServiceName>sriramktest</ServiceName> </HostedService> </HostedServices>
|
By playing with the URIs that the code hits, you can dig into your
services. For example, to get detailed information on sriramktest, you must switch the URI in Example 1 to the following: https://management.core.windows.net/BD38CFDF-C191-4B09-B299-F706985CE348/services/hostedservices/sriramktest?embed-detail=true
(again, using your subscription ID and your service’s name). This
returns the following XML:
<HostedService xmlns=http://schemas.microsoft.com/windowsazure
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Url>https://management.core.windows.net/BD38CFDF-C191-4B09-B299-
F706985CE348/services/hostedservices/sriramktest</Url>
<ServiceName>sriramktest</ServiceName>
<HostedServiceProperties>
<Description />
<Label>c3JpcmFta3Rlc3Q=</Label>
</HostedServiceProperties>
<Deployments>
<Deployment>
<Name>testdemodeployment</Name>
<DeploymentSlot>Production</DeploymentSlot>
<PrivateID>c3b7e18e2c03471aac754a3593c61f19</PrivateID>
<Status>Suspended</Status>
<Label>c29tZWxhYmVs</Label>
<Url>http://sriramktest.cloudapp.net/</Url>
<Configuration>...dGlvbj4=</Configuration>
<RoleInstanceList>
<RoleInstance>
<RoleName>WorkerRole1</RoleName>
<InstanceName>WorkerRole1_IN_0</InstanceName>
<InstanceStatus>Stopped</InstanceStatus>
</RoleInstance>
<RoleInstance>
<RoleName>WebRole1</RoleName>
<InstanceName>WebRole1_IN_0</InstanceName>
<InstanceStatus>Stopped</InstanceStatus>
</RoleInstance>
</RoleInstanceList>
<UpgradeDomainCount>1</UpgradeDomainCount>
</Deployment>
</Deployments>
</HostedService>
Note how this XML reflects detailed information on my service.
Apart from returning the name, its label, and its ID, it also returns
all the roles contained within, their instances, and each instance’s
status. This is your one-stop shop for all the status information you
need on your services.
Now, here’s a bait-and-switch tactic. You’ll almost never write
code such as this. Of course, if you’re a tool developer, you can write
your own library. But in almost all cases, you’re better off using the
sample client library available at http://code.msdn.microsoft.com/windowsazuresamples. This
provides a friendly .NET wrapper to use over the API.
For most of us, though, our primary interest is not in building
tools with the API, but rather to use it for our day-to-day management
tasks. For that, you should pick out one of the many tools that build on
top of the API. Arguably, the most important such tool is csmanage.
6. Using Csmanage
The file csmanage.exe is a
command-line tool that wraps on top of the Service
Management API to provide you with a command-line interface to Windows
Azure. It ships as a free sample, or as a sample with source. If you’re
planning to use the Service Management API, you’ll probably wind up
becoming very familiar with csmanage.
Note: Binaries and code are available at http://code.msdn.microsoft.com/windowsazuresamples.
After downloading csmanage and unzipping its contents, the first
thing you must do is to configure it with the certificate it should use,
and with your subscription ID. To do that, open csmanage.exe.config in the directory you
extracted to. You’ll see placeholders for SubscriptionID and CertificateThumbprint. Fill in these
placeholders with your subscription ID and the Thumbprint of the
certificate you created and uploaded. You can get the Thumbprint either
from the Windows Certificate Manager (Figure 2) or from the Windows Azure portal
(Figure 4). Example 3 shows a sample csmanage.exe.config file using the same
subscription ID and certificate used in the examples so far.
Example 3. Sample csmanage.exe.config file
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <bindings> <webHttpBinding> <binding name="WindowsAzureServiceManagement_WebHttpBinding" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"> <readerQuotas maxStringContentLength="1048576" maxBytesPerRead="131072" /> <security mode="Transport"> <transport clientCredentialType="Certificate" /> </security> </binding> </webHttpBinding> </bindings> <client> <endpoint name="WindowsAzureEndPoint" address="https://management.core.windows.net" binding="webHttpBinding" bindingConfiguration="WindowsAzureServiceManagement_WebHttpBinding" contract= "Microsoft.Samples.WindowsAzure.ServiceManagement.IServiceManagement" /> </client> </system.serviceModel> <appSettings> <add key="CheckServerCertificate" value="true"/> <!-- Insert your subscriptionId as shown by the Windows Azure developer portal --> <add key="SubscriptionId" value="BD38CFDF-C191-4B09-B299-F706985CE348"/> <!-- Insert your certificate thumbprint without spaces --> <add key="CertificateThumbprint" value="F89A1A38CBEE271C4B817507EB429ACD7C52B242"/> </appSettings> </configuration>
|
Once configured, csmanage is simple to use. Enter csmanage /? to get a listing of all the commands
supported. All csmanage.exe
operations have a 1:1 mapping to the underlying API they call, so it
provides a great way to learn how the API works as well.
Let’s start by using csmanage to do the same thing that Example 1 did: listing hosted services. Example 4 shows how this is done
with the formatted output.
Example 4. Csmanage listing hosted services
D:\csmanage>csmanage /list-hosted-services Using certificate: CN=Preconfigured Cert Listing HostedServices HostedServiceList contains 1 item(s). HostedService Name:sriramktest HostedService Url:https://management.core.windows.net/BD38CFDF-C191-4B09-B299- F706985CE348/services/hostedservices/sriramktest Operation ID: 4279aa416ba84eda9cf6c0d9a0ba076e HTTP Status Code: OK StatusDescription: OK
|
Apart from formatting the data structures returned by the API,
csmanage also shows you the operation ID of the API call. In the case of an error, or
for troubleshooting issues, you’ll need to tell the Microsoft Support
staff this ID to find out what went wrong.
Let’s do something more complex now. Creating a new deployment is
arguably the most important operation supported by the API, and probably
the most complex as well. Example 5 shows how to create
a new deployment and upload a package to staging. The code has been reformatted
slightly to help with readability.
Example 5. Creating a new deployment with csmanage
D:\csmanage>csmanage /create-deployment /hosted-service:sriramktest /name:mydeployment /slot:staging /label:somelabel /package:http://sriramk.blob.core.windows.net/packages/webnworker.cspkg /config:D:\ \webnworker\bin\Debug\Publish\ServiceConfiguration.cscfg
Using certificate: CN=Preconfigured Cert Creating Deployment... Name: mydeployment, Label: somelabel Operation ID: 47bc156f14a94180aa737887aa1c09a1 HTTP Status Code: Accepted StatusDescription: Accepted Waiting for async operation to complete: ..............Done Operation Status=Succeeded
|
Note the csmanage parameters highlighted in Figure 4. Apart from the name, label, and
slot (staging or production), csmanage must be told which
configuration to use, and which package to use. There’s one big
difference between the API and the Developer Portal shown here. The API
requires that any package be uploaded to Windows Azure blob storage
first, whereas the portal can accept packages directly from your local
filesystem.
At this point, if you go to the Developer Portal, you should see
the package in the staging slot.
However, it isn’t running. Let’s fix that by using csmanage again. Example 6 shows how.
Example 6. Running a deployment using csmanage
D:\ \csmanage>csmanage /update-deployment /status:running /slot:staging /hosted-service:sriramktest Using certificate: CN=Preconfigured Cert Updating DeploymentStatus Operation ID: af111bddb6ea4effb2cd03ac4e10c11a HTTP Status Code: Accepted StatusDescription: Accepted Waiting for async operation to complete: ...............Done Operation Status=Succeeded
|
Now you have a running deployment in the cloud without using the
Windows Azure Developer Portal at all. Csmanage is a handy little tool,
and you can imagine using it by invoking it from build scripts, tools,
and toy applications that must deploy to the cloud.
If you’re not calling the API from the Windows world, you have some extra work to
do. As of this writing, there are no csmanage-like tools available.
However, since the API is just REST-based, it is simple to script
common open source tools.
First, export your certificate to a .pfx file from the certificate store. You
can use the OpenSSL family of tools to convert the .pfx file to a PEM file, which plays better
with the non-Windows world:
$ openssl pkcs12 -in preconfig.pfx -out preconfig.pem
-nodes
Enter Import Password:
MAC verified OK
After this, calling an API is just a question of making the
right HTTP request. A widely used tool for constructing HTTP requests
is curl. Following is a sample curl command to list hosted
services:
$ curl -H "x-ms-version:2009-10-01" -E preconfig.pem
https://management.core.windows.net/BD38CFDF-C191-
4B09-
B299- F706985CE348/services/hostedservices